<template>

    <div style="border: 1px solid black; margin: 10px ; padding: 10px;">
        <el-container>
            <el-aside width="250px" style="background-color:aliceblue;">
                <img class="product-img" :src="tableData[0].goodsPhoto" alt="产品图"
                    style="width: 250px; height: 400px;" />
            </el-aside>
            <el-main style="margin: auto;">
                <div style="margin: 0px 0px;padding: auto;">
                    <h1>{{ tableData[0].goodsName }} </h1>
                    生成批次:{{ tableData[0].goodsBatch }}
                    保质期:{{ tableData[0].goodsExpiration }}天<br></br>
                    生产许可证号:{{ tableData[0].goodsLicense }}
                    生产企业:{{ tableData[0].goodsEnterprise }}
                </div>
                产品检验报告:
                <!--<el-upload v-model:file-list="fileList" action="http://localhost:5002/api/Upload/FileUpload"
                    list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                    :on-success="handleAvatarSuccess">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog> -->

                <el-upload v-model:file-list="fileList" action="http://localhost:5002/api/Upload/FileUpload"
                    list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                    :on-success="handleAvatarSuccess">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>

            </el-main>
            <el-aside width="300px">
                <el-button>修改基本信息</el-button>
                <el-button
                    @click="GoCodeData(tableData[0].goodsName, tableData[0].goodsBatch, tableData[0].goodsLicense)">导出溯源码</el-button>
            </el-aside>
        </el-container>
    </div>

    <div class="farm-info-container">
        <!-- 标签页 -->
        <el-tabs v-model="activeTab" class="tabs">
            <el-tab-pane label="养殖信息 " name="breed" @chang="GetCultData(), EnterpriseinfoGet()"></el-tab-pane>
            <el-tab-pane label="屠宰信息 " name="slaughter" @chang="GetSlaug()"></el-tab-pane>
            <el-tab-pane label="深加工信息 " name="processing"></el-tab-pane>
        </el-tabs>

        <!-- 养殖信息模块 -->
        <div class="module" v-if="activeTab === 'breed'">
            <span class="module-title">养殖信息</span>
            <el-button>设置</el-button>
            <div>
                品种:{{ CulData[0].cultivationVariety }}
                来源:{{ CulData[0].cultivationSource }} <br></br>
                饲养天数:{{ CulData[0].cultivationDays }}天
                饲料品牌:{{ CulData[0].cultivationBrand }}<br></br>
                饲养负责人:{{ CulData[0].cultivationLeader }}
                出栏日期:{{ moment(CulData[0].cultivationOutDate).format("YYYY年MM月DD日") }}
            </div>


            <!-- 保健信息模块 -->
            <div class="sub-module">
                <span class="module-title">保健信息</span>
                <el-button @click="onAddItem">新增行</el-button>


                <el-table :data="healthTableData" border style="width: 100%">

                    <el-table-column prop="days" label="饲养天数">
                        <template #default="scope">
                            <template v-if="scope.row.State">
                                <el-input v-model="scope.row.days" size="small" placeholder="请输入饲养天数"
                                    type="number"></el-input>
                            </template>
                            <template v-else>
                                {{ scope.row.days }}
                            </template>
                        </template>
                    </el-table-column>

                    <el-table-column prop="way" label="保健方式">
                        <template #default="scope">
                            <template v-if="scope.row.State">
                                <el-input v-model="scope.row.way" size="small" placeholder="请输入保健方式"
                                    type="number"></el-input>
                            </template>
                            <template v-else>
                                {{ scope.row.way }}
                            </template>
                        </template>
                    </el-table-column>


                    <el-table-column prop="method" label="保健方法">
                        <template #default="scope">
                            <template v-if="scope.row.State">
                                <el-input v-model="scope.row.method" size="small" placeholder="请输入饲养天数"
                                    type="number"></el-input>
                            </template>
                            <template v-else>
                                {{ scope.row.method }}
                            </template>
                        </template>
                    </el-table-column>


                    <el-table-column label="操作" align="left" width="180">
                        <template #default="scope">
                            <template v-if="scope.row.State">
                                <el-button type="primary" size="mini" @click="handleSave(scope.$index)" class="mr-1">
                                    保存
                                </el-button>
                                <el-button type="default" size="mini" @click="handleCancel(scope.$index)">
                                    取消
                                </el-button>
                            </template>
                            <template v-else>
                                <el-button type="text" size="mini" @click="handleEdit(scope.$index)"
                                    class="mr-1 text-blue-600">
                                    修改
                                </el-button>
                                <el-button type="text" size="mini" @click="handleDelete(scope.$index, scope.row.Id)"
                                    class="text-red-600">
                                    删除
                                </el-button>
                            </template>
                        </template>
                    </el-table-column>



                </el-table>
            </div>

            <!-- 动检证模块 -->
            <div class="sub-module">
                <div class="module-header">
                    <span class="module-title">动检证</span>
                </div>
                <div class="image-list">
                    <div class="image-item" v-for="(img, index) in images" :key="index">
                        <img :src="img" alt="动检证" class="cert-img">
                        <el-button type="text" class="close-btn" @click="removeImage(index)">×</el-button>
                    </div>
                    <div class="image-item add-item" @click="addImage">
                        <span class="plus">+</span>
                    </div>
                </div>
            </div>

            <div class="sub-module">
                <span class="module-title">企业信息</span>
                <el-button @click="">设置</el-button>
                <div>
                    养殖场:{{ EnterData[0].enterpriseFarms }}

                    负责人:{{ EnterData[0].enterpriseLeader }}

                    存栏数量:{{ EnterData[0].enterpriseNum }} 只
                </div>
            </div>

        </div>

        <!-- 屠宰信息、深加工信息模块可类似扩展，这里简单占位 -->
        <div class="module" v-else-if="activeTab === 'slaughter'">
            <span class="module-title">屠宰信息</span>
            <el-button>设置</el-button>
            <div>
                批次:{{ SlaugData[0].slaughterBatch }}

                到厂均重:{{ SlaugData[0].slaughterWeight }} 公斤<br></br>

                到厂时间:{{ moment(SlaugData[0].arrivaltime).format("YYYY年MM月DD日 HH:mm:ss") }}

                屠宰时间:{{ moment(SlaugData[0].slaughtertime).format("YYYY年MM月DD日 HH:mm:ss") }}
            </div>

            <div class="sub-module">
                <div class="module-header">
                    <span class="module-title">相关资质</span>
                </div>
            </div>

            <div class="sub-module">
                <span class="module-title">企业信息</span>
                <el-button @click="Slaugent()">设置</el-button>
                <div>
                    公司名称:{{ Slaugentter[0].seName }}

                    成立时间:{{ moment(Slaugentter[0].seFounded).format("YYYY年MM月DD日") }}<br></br>

                    公司地址:{{ Slaugentter[0].seAddress }}<br></br>

                    公司简介:{{ Slaugentter[0].sEintroduce }}
                </div>

            </div>

        </div>

        <div class="module" v-else-if="activeTab === 'processing'">
            <span class="module-title">深加工信息</span>
            <el-button>设置</el-button>

            <div>
                班组:{{ ProcData[0].processingTeam }}

                负责人:{{ ProcData[0].processingName }} 公斤<br></br>


            </div>
        </div>
    </div>


    <!-- 屠宰企业 添加弹框 -->
    <el-dialog v-model="dialogFormVisible" title="屠宰企业  " width="500">

        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="公司名称" prop="SEName">
                <el-input v-model="ruleForm.SEName" />
            </el-form-item>

            <el-form-item label="公司地址" prop="SEAddress">
                <el-cascader size="large" :options="pcaTextArr" v-model="ruleForm.SEAddress">

                </el-cascader>
            </el-form-item>

            <el-form-item label="成立时间" prop="SEFounded">
                <el-date-picker v-model="ruleForm.SEFounded" type="date" />
            </el-form-item>

            <el-form-item label="公司简介" prop="SEintroduce">
                <el-input v-model="ruleForm.SEintroduce" :rows="3" type="textarea" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    添加
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'

import { ElMessage, ElMessageBox } from 'element-plus'
import { Goblet, Plus } from '@element-plus/icons-vue'

import type { UploadProps, UploadUserFile } from 'element-plus'
import moment from 'moment'

import type { FormInstance, FormRules } from 'element-plus'

import {
    regionData,
    pcaTextArr,
    codeToText,
} from 'element-china-area-data'
import { el } from 'element-plus/es/locales.mjs'
import router from '@/router'

const UseRoute = useRoute();

//商品信息数据
const tableData = ref([{
    "id": null,
    "goodsId": null,
    "goodsName": "兔腿(小)",
    "goodsBatch": "20250819",
    "goodsExpiration": null,
    "goodsLicense": "sc211101027680",
    "goodsEnterprise": "成都爱吃兔食品加工有限公司",
    "goodsPhoto": "http://localhost:5002/images/a01.jpg",
    "createPeop": "admin",
    "createTime": "2025-08-19T18:51:22",
    "isDelete": false
}])


const getBasicData = reactive({
    id: UseRoute.query.id
})


// 显示的商品基本信息
const BasicinfoGet = () => {
    axios.get("http://localhost:5002/api/Goods/BasicinfoGet", { params: { Id: UseRoute.query.id } }).then(res => {
        console.log(res.data.iteims);

        tableData.value = res.data.iteims
        console.log(tableData.value)
    })
}

//产品检验报告
const imageUrl = ref('')
const imgs = reactive({
    GoodsId: getBasicData.id,
    ImgUrl: "",
    ImgType: '',
    BasicBatch: ''
})
const imgvisible = ref(false)
// 成功上传图片后的操作
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response);

    imgs.ImgUrl = "http://localhost:5002/" + response
    ImgCreate('产品检验报告')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/png' && rawFile.type != 'image/jpeg') {
        ElMessage.error('只支持png/jpg格式照片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不允许超过2MB!')
        return false
    }
    return true
}
const fileList = ref<UploadUserFile[]>([

])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
//删除图片
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

//实现 多图片上传
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
    console.log(fileList);
}

//保存图片q
const ImgCreate = (ImgType: any) => {
    imgs.GoodsId = UseRoute.query.id
    imgs.ImgType = ImgType
    console.log(imgs);

    axios.post("http://localhost:5002/api/Img/ImgCreate", imgs).then(res => {
        if (res.data.code == 200) {
            console.log(res);
            ElMessage.success("上传成功");
        }
        else {
            console.log(res);
            ElMessage.error("上传失败");
        }
    })
}

const GetImgData = () => {
    axios.get("http://localhost:5002/api/Img/ImgGet", {
        params: {
            GoodsId: UseRoute.query.id,
            ImgType: '产品检验报告'
        }
    }).then(res => {
        console.log(res.data.data);

        res.data.data.map((x: any) => x.imageUrl).forEach(function (item: any) {
            fileList.value = res.data.data.map((x: any) => {
                name: x.imgUrl.split('/').pop() || 'images'
                url: x.imgUrl
            })
            imgs.ImgUrl = res.data.data.map((x: any) => x.imgUrl)
        })
        console.log(fileList.value);

    })
}


//跳转那个信息的
const activeTab = ref('breed');

const CulData = ref([{
    "cultivationVariety": "伊拉兔",
    "cultivationSource": "采购",
    "cultivationDays": 90,
    "cultivationBrand": "大北兔",
    "cultivationLeader": "小陈",
    "cultivationOutDate": "2025-07-14T09:21:30.748596",
}])
const EnterData = ref([{
    "enterpriseFarms": "四川锦祥养殖基地",
    "enterpriseLeader": "X总",
    "enterpriseNum": 3200,
    "goodsId": 4
}])
// 对应的养殖信息
const GetCultData = () => {
    axios.get("http://localhost:5002/api/Cultivationinfo/CultivationinfoGet", {
        params: {
            Id: getBasicData.id
        }
    }).then(res => {
        CulData.value = res.data.iteims
        console.log(CulData.value)
    })
}

//对应的养殖企业信息
const EnterpriseinfoGet = () => {
    axios.get("http://localhost:5002/api/Cultivationinfo/EnterpriseinfoGet", {
        params: {
            Id: getBasicData.id
        }
    }).then(res => {
        EnterData.value = res.data.data
        console.log(EnterData.value)
    })
}

// 保健信息表格数据
const healthTableData = ref([
    { Id: 1, days: 30, way: '兔瘟疫苗', method: '皮下注射', State: false },
    { Id: 2, days: 45, way: '巴二联苗', method: '皮下注射', State: false }
]);

const onAddItem = () => {
    healthTableData.value.push({
        Id: 0,
        days: '',
        way: '',
        method: '',
        State: true
    })
}

// 动检证图片
const images = ref(['https://example.com/cert.jpg']); // 实际替换为你的图片地址

// 添加动检证图片（示例，实际可结合上传组件）
const addImage = () => {
    // 这里简单模拟，实际可通过 el-upload 组件上传
    images.value.push('https://example.com/new-cert.jpg');
};

// 删除动检证图片
const removeImage = (index: any) => {
    images.value.splice(index, 1);
};

// 保健行的修改
const handleEdit = (index: any) => {
    // 保存原始数据用于取消操作时恢复
    healthTableData.value[index].originData = { ...tableData.value[index] };
    healthTableData.value[index].State = true;
};

// 保健行的保存
const handleSave = (index: any) => {
    const row = healthTableData.value[index];

    // 简单验证
    if (!row.days || !row.way || !row.method) {
        ElMessage.warning('请填写完整信息');
        return;
    }

    axios.post("http://localhost:5002/api/Cultivationinfo/HealthUpd", row).then(res => {
        if (res.data.code == 200) {
            ElMessage.success(res.data.meg)
        }
        else {
            ElMessage.error(res.data.meg)
        }
    })

    // 标记为非编辑状态
    row.State = false;
    ElMessage.success('保存成功');

    // 实际项目中这里可以调用API保存到后端
    // console.log('保存数据:', row);
};

// 保健行的取消
const handleCancel = (index: any) => {
    const row = healthTableData.value[index];

    // 如果是新增的空行，取消时直接删除
    if (row.Id.toString().length > 10 && // 判断是否是时间戳ID
        !row.days && !row.method && !row.way) {
        tableData.value.splice(index, 1);
    } else {
        // 恢复原始数据
        if (row.originData) {
            tableData.value[index] = { ...row.originData };
        } else {
            row.State = false;
        }
    }
};

// 保健行的删除
const handleDelete = (index: any, Id: any) => {

    ElMessageBox.confirm(
        '您确定要删除吗?',
        '删除警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {

            axios.put("http://localhost:5002/api/Cultivationinfo/HealthDel", { Id: Id }).then(res => {
                if (res.data.code == 200) {
                    //删除索引
                    tableData.value.splice(index, 1);
                    ElMessage.success('删除成功');
                }
                else {
                    ElMessage.error("删除失败");
                }
            })


            // ElMessage({
            //     type: 'success',
            //     message: 'Delete completed',
            // })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '您取消了删除',
            })
        })
};

//屠宰 
const SlaugData = ref([{
    "slaughterBatch": "20250820",
    "arrivaltime": "2025-07-18T13:51:30.345789",
    "slaughterWeight": "20",
    "slaughtertime": "2025-07-18T14:55:34.298615",
}])

const GetSlaug = () => {
    axios.get("http://localhost:5002/api/Slaughter/SlaughterGet", {
        params: {
            GoodsId: getBasicData.id
        }
    }).then(res => {
        SlaugData.value = res.data.data
    })
}

//添加屠宰企业信息
const dialogFormVisible = ref(false)//屠宰企业 弹框

const Slaugent = () => {
    dialogFormVisible.value = true
}

interface RuleForm {
    SEName: string
    SEAddress: string
    SEFounded: string
    SEintroduce: string
    GoodsId: any
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    SEName: '',
    SEAddress: '',
    SEFounded: '',
    SEintroduce: '',
    GoodsId: UseRoute.query.id
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
    SEName: [
        { required: true, message: '屠宰企业名称不能为空', trigger: 'blur' },
    ],
    SEAddress: [
        { required: true, message: '屠宰企业地址不能为空', trigger: 'change', },
    ],
    SEFounded: [
        { required: true, message: '成立时间不能为空', trigger: 'blur' },
    ],
    SEintroduce: [
        { required: true, message: '企业简介不能为空', trigger: 'change', },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')

            ruleForm.SEAddress = ruleForm.SEAddress.toString()

            axios.post("http://localhost:5002/api/Slaughter/SlaugHteringentAdd", ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("更新屠宰企业成功");
                    dialogFormVisible.value = false
                }
                else {
                    ElMessage.success("更新屠宰企业失败");
                    dialogFormVisible.value = false
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const Slaugentter = ref([{
    "seName": "四川锦祥食品有限公司",
    "seAddress": "河北省,秦皇岛市,山海关区",
    "seFounded": "2025-08-24T16:00:00",
    "sEintroduce": "公司简介公司简介公司简介公司简介",
}])

const ProcData = ref([{
    "processingTeam": "一组",
    "processingName": "小陈",
}])

const GoCodeData = (Goodname: any, Goodbatch: any, Goodlicense: any) => {
    localStorage.setItem("Goodname", Goodname)  //商品名称
    localStorage.setItem("Goodbatch", Goodbatch)  //生产批次
    localStorage.setItem("Goodlicense", Goodlicense)  //生产许可证号
    router.push("/Code")
}

onMounted(() => {
    BasicinfoGet();//对应的养殖
    EnterpriseinfoGet()//对应的养殖企业
    GetImgData()
})

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>

<style scoped>
.farm-info-container {
    padding: 20px;
}

.tabs {
    margin-bottom: 20px;
}

.module {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.module-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.module-title {
    font-size: 16px;
    font-weight: bold;
}

.info-item {
    margin-bottom: 10px;
}

.label {
    display: inline-block;
    width: 80px;
    text-align: right;
    margin-right: 10px;
}

.sub-module {
    margin-top: 20px;
}

.image-list {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.image-item {
    width: 120px;
    height: 120px;
    position: relative;
}

.cert-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 4px;
}

.close-btn {
    position: absolute;
    top: 2px;
    right: 2px;
    color: #fff;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    padding: 2px 6px;
}

.add-item {
    border: 1px dashed #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.plus {
    font-size: 24px;
    color: #ccc;
}
</style>